<?php
session_start();

function GenerateKeywordCriteria(&$item) {
	$item = trim($item);
	if ($item != '')
		$item = 'AND LCASE(title) LIKE \'%'.str_replace('\'', '"', $item).'%\'';
}

// This search function will search through the titles live, it is really inefficient.
// It can be improved by using inverted page table.
function Search($words) {
	$req = '';
	if (count($words) > 0) {
		array_walk($words, 'GenerateKeywordCriteria');
		$req = implode(' ', $words);
	}
	$req = 'SELECT COALESCE(b.title, \'title not available\') AS title, b.abstract, tmp.*
					FROM bibtex AS b, (
						SELECT b.id, COUNT(r.id) AS res_count, COALESCE(SUM(read.count), 0) AS read_count, COALESCE(SUM(rate.count), 0) AS rate_count
						FROM resource AS r JOIN bibtex AS b ON r.bibtexid=b.id '.$req.'
						LEFT JOIN (SELECT resourceid, COUNT(*) AS count FROM reading GROUP BY resourceid) AS read ON read.resourceid=r.id
						LEFT JOIN (SELECT resourceid, COUNT(*) AS count FROM rateresource GROUP BY resourceid) AS rate ON rate.resourceid=r.id
						GROUP BY b.id
					) AS tmp WHERE tmp.id = b.id';
	return DBExecute($req);
}

$startTime = microtime(true);

// Get data from POST string.
$type = $_REQUEST['type'];
$preset = $_REQUEST['preset'];  // queries that are preset, does not depend on filters
$query = $_REQUEST['q'];

// Connect to the DB.
require_once 'include/config.lib.php';
require_once 'include/database.lib.php';

ConnectToDB();

$data = NULL;

if ($type == 'person') {
	$data = array();
	$personReq = DBExecute('SELECT p.id, COALESCE(p.name, p.username, \'no name\') AS name, p.description, p.email FROM person AS p');
	while ($row = $personReq->fetchAssocRow()) {
		array_push($data, $row);
	}
} else if ($type == 'paper') {
	$data = array();
	$paperReq = NULL;
	if (isset($preset) && $preset != '') {
		$table = NULL;
		switch ($preset) {
			case 'read': $table = 'reading'; break;
			case 'reviewed': $table = 'rateresource'; break;
			case 'annotated': $table = 'annotation'; break;
		}
		if (!isset($table)) die('cannot find preset query');
		$paperReq = DBExecute('	SELECT b.id, COALESCE(b.title, \'title not available\') AS title, SUM(tmp.count) AS count
														FROM resource AS r, bibtex AS b, (SELECT resourceid, COUNT(*) AS count FROM '.$table.' GROUP BY resourceid) AS tmp
														WHERE r.bibtexid=b.id AND tmp.resourceid=r.id
														GROUP BY b.id, title
														ORDER BY count DESC FETCH FIRST 5 ROWS ONLY');
	} else {
		$paperReq = Search(explode(' ', $query));
	}
	while ($row = $paperReq->fetchAssocRow()) {
		array_push($data, $row);
	}
}

if (isset($data)) {
	header('Content-type: application/json');
	echo json_encode(array('type' => $type, 'count' => count($data), 'time' => microtime(true) - $startTime, 'result' => $data));
} else {
	die('data generation failed');
}
?>